package com.catmiw.swt;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.output.Format.TextMode;

public class EnglishWordsXmlHandler {
	private String xmlfilename;
	private Document document;
	private SAXBuilder builder = new SAXBuilder();

	public EnglishWordsXmlHandler(String xmlfilename) {
		this.xmlfilename = xmlfilename;
	}

	public Word loadWord(String wordid) {
		if (document == null) {
			try {
				document = builder.build(new File(xmlfilename));
			} catch (JDOMException e) {
				return null;
			} catch (IOException e) {
				return null;
			}
			if (document == null)
				return null;
		}
		Word word = null;
		Element root = document.getRootElement(); // 取得根节点

		List<Element> list = root.getChildren("word");
		for (int i = 0; i < list.size(); i++) {
			Element e = list.get(i);// 取得子节点
			if (e.getAttribute("id").getValue().equals(wordid)) {
				word = new Word();
				word.setId(wordid);

				List<Meaning> ms = new ArrayList<Meaning>();
				word.setMeanings(ms);
				
				String str=e.getAttributeValue("plural");
				if (str!=null)
					word.setPlural(str.trim());
				
				str=e.getAttributeValue("thirdPersonSingular");
				if (str!=null)
					word.setThirdPersonSingular(str.trim());
				
				str=e.getAttributeValue("presentParticiple");
				if (str!=null)
					word.setPresentParticiple(str.trim());
				
				Element ems = e.getChild("meanings");
				if (ems != null) {
					List<Element> l2 = ems.getChildren("meaning");
					if (l2 != null) {
						for (int j = 0; j < l2.size(); j++) {
							Meaning mx = new Meaning();
							Element ee=l2.get(j);
							mx.setOrder(Integer.parseInt(ee.getAttribute("order").getValue()));
							mx.setPartOfSpeech(ee.getAttribute("partOfSpeech").getValue());
							if (ee.getAttribute("english")!=null)
								mx.setEnglish(ee.getAttribute("english").getValue());
							if (ee.getAttribute("chinese")!=null)
								mx.setChinese(ee.getAttribute("chinese").getValue());
							ms.add(mx);
						}
					}
				}
				break;
			}
		}

		return word;
	}

	public void checkWordElement(Element e){
		Element meanings=e.getChild("meanings");
		if (meanings==null)
			return;
		
		List<Element> meanlist=meanings.getChildren("meaning");
		if (meanlist==null)
			return;
		for (int i=meanlist.size()-1;i>=0;i--){
			Element m=meanlist.get(i);
			String tt=m.getAttributeValue("partOfSpeech");
			String tt2=m.getAttributeValue("chinese");
			if ("".equals(tt)&&(tt2==null||"".equals(tt2))){
				meanings.removeContent(m);
			}
			if (tt.startsWith("See also")){
				meanings.removeContent(m);
			}
		}
		meanlist=meanings.getChildren("meaning");
		for (int i=0;i<meanlist.size();i++){
			Element m=meanlist.get(i);
			m.setAttribute("order",""+(i+1));
		}
	}
	
	public boolean addWordToDocument(Word word) {
		Element root = document.getRootElement();
		List<Element> children = root.getChildren();
		for (Element e : children) {
			if (e.getAttribute("id").getValue().equals(word.getId())) {
				return false;
			}
		}

		try {
			String temp=word.toString().replace("&", "_");
			Element e = builder.build(
					new ByteArrayInputStream(temp.getBytes()))
					.getRootElement();
			e.detach();
			checkWordElement(e);
			
			root.addContent(e);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}
	
	public void saveToFile(){
		synchronized (document) {
				// 四：将上述内容写入XML
				XMLOutputter out = new XMLOutputter();
				Format format = out.getFormat();
				format.setIndent("\t");
				format.setTextMode(TextMode.TRIM);
				format.setEncoding("UTF-8");
				try {
					out.output(document, new FileOutputStream(new File(
							xmlfilename)));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
	}

	public void storeWord(Word word) {
		if (document == null) {
			SAXBuilder builder = new SAXBuilder();
			try {
				document = builder.build(new File(xmlfilename));
			} catch (JDOMException e) {
			} catch (IOException e) {
			}
			if (document == null) {
				Element root = new Element("words");
				document = new Document(root);
			}
		}
		if (addWordToDocument(word)) {
			saveToFile();
		}
	}

	public void deleteRepeat(){
		Element root=document.getRootElement();
		Element e=document.detachRootElement();
		e.removeChild("word");

		List<Element> eles=root.getChildren();
		Set<String> m=new HashSet<String>();
		for (int i=eles.size()-1;i>=0;i--){
			Element ee=eles.get(i);
			String temp=ee.getAttributeValue("id");
			if (m.contains(temp)){
				System.out.println(temp);
			}
			else 
				m.add(temp);
		}
	}
	public void findRepeat(){
		Element e=document.getRootElement();
		List<Element> eles=e.getChildren();
		Set<String> m=new HashSet<String>();
		for (Element ee:eles){
			String temp=ee.getAttributeValue("id");
			if (m.contains(temp))
				System.out.println(temp);
			else 
				m.add(temp);
		}
	}
	
	public static void main(String[] args){
		List<String> listx=new ArrayList<String>();
		
		EnglishWordsXmlHandler xmlh=new EnglishWordsXmlHandler("D:\\studyassist\\config\\englishwords.xml");
		xmlh.loadWord("1");
		
		Element root = xmlh.document.getRootElement(); // 取得根节点

		List<Element> list = root.getChildren("word");
		for (int i = 0; i < list.size(); i++) {
			Element e = list.get(i);
			System.out.println(e.getAttributeValue("id"));
			List<Element> list2 = e.getChild("meanings").getChildren();
			for (Element ex:list2){
				String ttx=ex.getAttributeValue("partOfSpeech");
				if (!listx.contains(ttx)){
					listx.add(ttx);
				}
				//System.out.println(ex.getAttributeValue("partOfSpeech"));
			}
			//xmlh.checkWordElement(e);		
		}
		Collections.sort(listx);
		for (String m:listx){
			System.out.println(m);
		}
	}
}
